/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sct_beans;

import com.google.common.io.Files;
import entities.TestResult;
import entities.TestItem;
import executor.ExecutionResult;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import testing.*;
import testingimpl.testmethodservice.TestMethodService;

/**
 *
 * @author ryuju
 */
@Stateless
@LocalBean
public class SourceCodeTest {
    @EJB
    private SCExecuteBean executeBean;

    @EJB
    private TestResultMsgSender testResultMsgSender;

    private void printLog(String msg)
    {
        Logger.getLogger(SourceCodeTest.class.getName()).log(Level.INFO, "[SourceCodeTester] " + msg);
    }
    
    
    public void runTest(TestItem tu) {
        TestResult testResult = new TestResult();
        try {
            printLog("Testing start, Submission ID: " + tu.getSubmitID());
            
            ITestMethodService tms = new TestMethodService();
            ITestMethod tm = tms.getTestMethod(tu);

            printLog("Execution start...");
            // execute
            ExecutionResult execResult = executeBean.execute(tu);
            printLog("Execution success!");
            
            
            printLog("Test execution result...");
            // test
            testResult = tm.doTest(tu, execResult);
            
        } catch (TestingException ex) {
            printLog(ex.getMessage());
            testResult = makeFailTestResult(tu, ex.getMessage());
        }
        catch(Exception e)
        {
            printLog(e.getMessage());
            testResult = makeFailTestResult(tu, e.getMessage());
        }
        
        printLog("Send TestReuslt.");
        // send TestResult
        testResultMsgSender.sendTestResultMsg(testResult);
    }

    private TestResult makeFailTestResult(TestItem testItem, String errMsg) {
        TestResult tr = new TestResult();
        tr.setSubmitID(testItem.getSubmitID());
        tr.setErrMsg(errMsg);
        tr.setExecuted(false);
        tr.setScore(0);
        tr.setTestTime(0);
        tr.setExecutionTime(0);
        return tr;
    }
}
